// components/recipe/index.js
import {
  request
} from '../../api/index';
import {
  searchData,
  numSettingsType
} from '../../dataSource';
import {
  _list
} from '../../api/ingredients-parent'
Component({
  options: {

  },
  /**
   * 组件的属性列表
   */
  properties: {
    root: {
      type: Boolean,
      observer(value) {
        this.setData({
          isRoot: value
        })
      }
    },
    show: {
      type: Boolean
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    columnsList: [],
    refresh: false,
    onLoading: false,
    total: 0,
    type: numSettingsType.INGREDIENTS,
    status: null,
    _parentList: [],
    options: [{
        text: '未发布',
        value: 'TO_BE_ANNOUNCED',
        color: '#1989fa'
      },
      {
        text: '已发布',
        value: 'ANNOUNCED',
        color: '#07c160'
      },
      {
        text: '已挂起',
        value: 'STOP',
        color: '#ff976a'
      },
      {
        text: '不限',
        value: '',
        color: 'rgba(0, 0, 0, 0.35)'
      }
    ],
    page: {
      currentPage: 1,
      size: 10
    },
    searchData,
    search: {
      picker: false
    },

    isRoot: true
  },

  /**
   * 组件的方法列表
   */
  methods: {

    onAddMaterial(event) {
      wx.navigateTo({
        url: '../../pages/material/index',
      })
    },
    toEddit(event) {
      const id = event.currentTarget.dataset.item.id;
      wx.navigateTo({
        url: '../../pages/material/index?id=' + id,
      })
    },
    onStatusChange(event) {
      const index = event.currentTarget.dataset.index;
      const columnsList = this.data.columnsList;
      columnsList[index].status = event.detail;
      this.setData({
        columnsList
      })
    },
    onStatusChangeFetch(event) {
      const status = event.detail;
      const page = Object.assign({}, this.data.page, {
        currentPage: 1
      })
      this.setData({
        page,
        status: status || status !== '' ? status : null
      })
      this.fetchIngredients();
    },
    /**
     * 配方列表
     */
    fetchIngredients(loading = true) {
      loading && wx.showLoading({
        title: '加载中',
      })
      request.ingredientsSearch({
        ...this.data.searchData,
        status: this.data.status || null,
        ...this.data.page
      }, (e) => {
        this.setData({
          columnsList: e.records.map(it => {
            return {
              ...it,
              parentName: this.data._parentList.find(item => item.id === it.parentId)?.name
            }
          }),
          total: e.total
        })
        loading && wx.hideLoading();
      })
    },
    showLoading() {
      wx.showLoading({
        title: '加载中'
      })
      setTimeout(wx.hideLoading, 500)
    },
    delectItem(event) {
      if (!getApp().globalData.root) {
        wx.showToast({
          title: '管理员可操作',
          icon: 'error'
        })
        return
      }
      const _this = this;
      wx.showModal({
        title: '提示',
        content: '确定要删除吗?',
        success(res) {
          if (res.confirm) {
            _this.delect(event.currentTarget.dataset.value);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    delect(target) {
      request.ingredientsRemove(target, () => {
        this.setData({
          columnsList: this.data.columnsList.filter(it => {
            return it.id !== target.id
          })
        })
      })
    },
    onRefresh() {
      this.setData({
        refresh: true,
        page: {
          ...this.data.page,
          currentPage: 1
        }
      })
      this.fetchIngredients(false);
      setTimeout(() => {
        this.setData({
          refresh: false
        })
      }, 1200)
    },
    onRefreshEnd() {
      this.setData({
        refresh: false
      })
    },
    onScrollLoad() {
      if (this.data.total > this.data.columnsList.length) {
        this.setData({
          onLoading: true,
          page: {
            ...this.data.page,
            currentPage: this.data.page.currentPage + 1
          }
        })
        this.loadData();
        setTimeout(() => {
          this.setData({
            onLoading: false
          })
        }, 1200)
      }
    },

    loadData() {
      request.ingredientsSearch({
        ...this.data.page,
        status: this.data.status || null,
        ...this.data.searchData
      }, (e) => {
        this.setData({
          columnsList: [...this.data.columnsList, ...(e.records.map(it => {
            return {
              ...it,
              parentName: this.data._parentList.find(item => item.id === it.parentId)?.name
            }
          }))],
          total: e.total,
          page: {
            ...this.data.page,
            currentPage: e.current
          }
        })
      }, function (e) {
        Toast({
          message: e,
          position: 'bottom'
        });
      })
    },
    onSearch(event) {
      const value = event.detail;
      this.setData({
        searchData: value,
        page: {
          currentPage: 1,
          size: 10
        }
      })
      this.showLoading();
      this.fetchIngredients()
    },
    statusPickerOpen() {
      this.setData({
        statusPickerShow: true
      })
    },
    showLoading() {
      wx.showLoading({
        title: '加载中'
      })
      setTimeout(wx.hideLoading, 500)
    },
    showSearch(event) {
      this.setData({
        search: {
          ...this.data.search,
          picker: true
        }
      })

    },
    hideSearch(event) {
      this.setData({
        search: {
          ...this.data.search,
          picker: false
        }
      })

    },
    async fetchParentId() {
      return new Promise((resolve, reject) => {
        _list({}, res => {
          this.setData({
            _parentList: res
          })
          resolve();
        }, reject)

      })
    },
  },
  pageLifetimes: {
    async show() {

      this.setData({
        total: 0,
        page: {
          currentPage: 1,
          size: 10
        },
        name: '',
        isRoot: wx.getStorageSync('root')
      })
      await this.fetchParentId();
      this.fetchIngredients();
    }
  }
})